package com.windchime.blog.controller;

import com.github.pagehelper.PageInfo;
import com.windchime.blog.entity.Blog;
import com.windchime.blog.entity.Type;
import com.windchime.blog.service.BlogService;
import com.windchime.blog.service.TypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
public class FrontTypeController {

    @Autowired
    private TypeService typeService;

    @Autowired
    private BlogService blogService;

    /**
     * 分类页面
     * @param model 传值
     * @param page 当前页
     * @param id 分类ID
     * @return types
     */
    @GetMapping("/types")
    public String types(Model model, @RequestParam(defaultValue = "1", value = "page") Integer page, @RequestParam(defaultValue = "", value = "id") Integer id) {
        List<Type> types = typeService.list();

        //设置每个分类有多少篇博客
        for (Type type : types) {
            Integer typeHasBlogs = blogService.typeHasBlogsByTypeId(type.getId());
            type.setTypeHasBlogs(typeHasBlogs);
        }

        //如果等于null代表从导航条进入的
        if (id == null) {
            id = types.get(0).getId();
        }
        model.addAttribute("types", types);
        model.addAttribute("activeTypeId", id);

        //设置每个分类ID下的博客
        Integer limit = 5;
        PageInfo<Blog> blogs = blogService.selectBlogListByTypeId(page, limit, id);
        for (Blog blog : blogs.getList()) {
            blog.setTypeName(typeService.getById(blog.getTypeId()).getName());
        }
        model.addAttribute("blogs", blogs);

        return "types";
    }
}
